<script>
import render from '@/components/Render/render.js'
import { getAuthenticationHeader } from '@/utils/store'

const ruleTrigger = {
  'el-input': 'blur',
  'el-input-number': 'blur',
  'el-select': 'change',
  'el-radio-group': 'change',
  'el-checkbox-group': 'change',
  'el-cascader': 'change',
  'el-time-picker': 'change',
  'el-date-picker': 'change',
  'el-rate': 'change'
}

const layouts = {
  colFormItem(h, scheme) {
    const config = scheme.__config__
    const listeners = buildListeners.call(this, scheme)

    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null
    if (config.showLabel === false) labelWidth = '0'
    return (
      <el-col span={config.span}>
        <el-form-item label-width={labelWidth} prop={scheme.__vModel__}
                      label={config.showLabel ? config.label : ''}>
          <render conf={scheme} on={listeners} />
        </el-form-item>
      </el-col>
    )
  },
  rowFormItem(h, scheme) {
    let child = renderChildren.apply(this, arguments)
    if (scheme.type === 'flex') {
      child = <el-row type={scheme.type} justify={scheme.justify} align={scheme.align}>
        {child}
      </el-row>
    }
    return (
      <el-col span={scheme.span}>
        <el-row gutter={scheme.gutter}>
          {child}
        </el-row>
      </el-col>
    )
  }
}

function renderFrom(h) {
  const { formConfCopy } = this
  return (
    <el-row gutter={formConfCopy.gutter}>
      <el-form
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        label-width={`${formConfCopy.labelWidth}px`}
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, formConfCopy.fields)}
        {formConfCopy.formBtns && formBtns.call(this, h)}
      </el-form>
    </el-row>
  )
}

function formBtns(h) {
  return <el-col>
    <el-form-item style="margin-left: -100px!important;text-align: center;">
      <el-button type="primary" onClick={this.submitForm}>提交</el-button>
      <el-button onClick={this.closeForm}>关闭</el-button>
    </el-form-item>
  </el-col>
}

function renderFormItem(h, elementList) {
  if (elementList) {
    const that = this
    const data = this[this.formConf.formModel]

    return elementList.map(scheme => {
      const config = scheme.__config__
      const layout = layouts[config.layout]

      // 解决 el-upload 上传的问题
      const vModel = scheme.__vModel__
      const val = data[vModel]
      if (scheme.__config__.tag === 'el-upload') {
        // 回显图片
        scheme['file-list'] = (val || []).map(url => ({ name: url, url }))
        // 上传地址 + 请求头
        scheme.action = process.env.VUE_APP_URL_PREFIX + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/upload`
        scheme.headers = getAuthenticationHeader()
        // 注意 on-success 不能绑定箭头函数！！！
        scheme['on-success'] = function (response, file, fileList) {
          if (response.code !== 0) {
            return;
          }
          // 添加到 data 中
          const prev = data[vModel] || []
          this.$set(data, vModel, [
            ...prev,
            response.data
          ])
          // 发起表单校验
          that.$refs[that.formConf.formRef].validateField(vModel)
        }
        // 注意 on-remove 不能绑定箭头函数！！！
        scheme['on-remove'] = function (file, fileList) {
          // 移除从 data 中
          const prev = data[vModel] || []
          const index = prev.indexOf(file.response.data)
          if (index === -1) {
            return
          }
          prev.splice(index, 1) // 直接移除即可，无需重复 set，因为 array 是引用
          // 发起表单校验
          that.$refs[that.formConf.formRef].validateField(vModel)
        }
      } else if (scheme.__config__.tag === 'el-date-picker' || scheme.__config__.tag === 'el-checkbox-group') {
        if (scheme.__config__.defaultValue && scheme.__config__.defaultValue.constructor !== Array) {
          scheme.__config__.defaultValue = scheme.__config__.defaultValue.split(',')
        }
      }

      if (layout) {
        return layout.call(this, h, scheme)
      }
      throw new Error(`没有与${config.layout}匹配的layout`)
    })
  }
}

function renderChildren(h, scheme) {
  const config = scheme.__config__
  if (!Array.isArray(config.children)) return null
  return renderFormItem.call(this, h, config.children)
}

function setValue(event, config, scheme) {
  this.$set(config, 'defaultValue', event)
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event)
  // this.$emit('updateField', this[this.formConf.formModel], scheme.__vModel__)
}

function buildListeners(scheme) {
  const config = scheme.__config__
  const methods = this.formConf.__methods__ || {}
  const listeners = {}

  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach(key => {
    listeners[key] = event => methods[key].call(this, event)
  })
  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = event => setValue.call(this, event, config, scheme)

  return listeners
}

export default {
  components: {
    render
  },
  props: {
    formConf: {
      type: Object,
      required: true
    }
  },
  data() {
    const data = {
      formConfCopy: this.$api.deepClone(this.formConf),
      [this.formConf.formModel]: {},
      [this.formConf.formRules]: {}
    }
    this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel])
    this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules])
    return data
  },
  methods: {
    initFormData(componentList, formData) {
      if (componentList) {
        componentList.forEach(cur => {
          this.buildOptionMethod(cur)
          const config = cur.__config__
          if (cur.__vModel__) {
            formData[cur.__vModel__] = config.defaultValue
            // 初始化文件列表
            if (cur.action && config.defaultValue) {
              cur['file-list'] = config.defaultValue
            }
          }
          if (cur.action) {
            cur['headers'] = getAuthenticationHeader()
            cur['on-success'] = (response, file, fileList) => {
              formData[cur.__vModel__] = fileList
              if (response.code === 200 && fileList) {
                config.defaultValue = fileList
                config.defaultValue.map(file_ => {
                  if (file.name === file_.name) {
                    file_.id = response.param
                  }
                  return file_
                })
              }
            }
          }
          if (config.children) this.initFormData(config.children, formData)
        })
      }
    },
    // 特殊处理的 Option
    buildOptionMethod(scheme) {
      const config = scheme.__config__
      if (config && config.tag === 'el-cascader' || config.tag === 'el-checkbox-group'
        || config.tag === 'el-radio-group' || config.tag === 'el-select') {
        if (config.dataType === 'dynamic') {
          this.$axios({
            method: config.method,
            url: config.url,
            headers: getAuthenticationHeader()
          }).then(response => {
            const { data } = response.param
            scheme[config.dataConsumer] = data[config.dataKey]
          })
        }
      }
    },
    buildRules(componentList, rules) {
      if (componentList) {
        componentList.forEach(cur => {
          const config = cur.__config__
          if (Array.isArray(config.regList)) {
            if (config.required) {
              const required = {required: config.required, message: cur.placeholder}
              if (Array.isArray(config.defaultValue)) {
                required.type = 'array'
                required.message = `请至少选择一个${config.label}`
              }
              required.message === undefined && (required.message = `${config.label}不能为空`)
              config.regList.push(required)
            }
            rules[cur.__vModel__] = config.regList.map(item => {
              item.pattern && (item.pattern = eval(item.pattern))
              item.trigger = ruleTrigger && ruleTrigger[config.tag]
              return item
            })
          }
          if (config.children) this.buildRules(config.children, rules)
        })
      }
    },
    resetForm() {
      this.formConfCopy = this.$api.deepClone(this.formConf)
      this.$refs[this.formConf.formRef].resetFields()
    },
    submitForm() {
      this.$refs[this.formConf.formRef].validate(valid => {
        if (!valid) return false
        // 触发 submit 事件
        this.$emit('submit', {
          conf: this.formConfCopy,
          values: this[this.formConf.formModel]
        })
        return true
      })
    },
    closeForm() {
      this.resetForm()
      this.$emit('close')
    },
    getData() {
      this.$refs[this.formConf.formRef].validate(valid => {
        if (!valid) return false

        this.$emit('getData', this.formConfCopy)
        return true
      })
    }
  },
  render(h) {
    return renderFrom.call(this, h)
  }
}
</script>
